package com.dommy.tab.util;

import com.dommy.tab.pojo.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * UserUtil
 * Created by 光头 on 2020/7/5.
 */

public class UserUtil {
    public static User  USER =  null;
    public static String USER_ID =  null;

    public static  User getUser(String userName,String passWord){
        int time =0;
        UserLogin(userName,passWord);
        while(USER == null && time < 8){
            try {
                time++;
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return USER;
    }

    public static User UserLogin(String userName,String passWord){
        FormBody formBody = new FormBody
                .Builder()
                .add("userName",userName)
                .add("passWord",passWord)
                .build();
        final Request request = new Request
                .Builder()
                .post(formBody)
                .url(MyUrlUtil.LOGIN_URL)
                .build();
        new OkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                sout
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 200) {
                        jsonObject = new JSONObject(jsonObject.get("data").toString());
                        USER = new User();
                        USER.id =jsonObject.getInt("id");
                        USER_ID = "/"+USER.id;
                        WaterUtil.INIT();
                        USER.userName =(String)jsonObject.get("userName");
                        USER.level = jsonObject.getInt("level");
                        USER.normal = jsonObject.getInt("normal");
                        USER.createTime = jsonObject.getString("createTime");
                        USER.updateTime = jsonObject.getString("updateTime");
                    }else{
                        return ;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return  USER;

    }
}
